package com.sencorsta.ids.common.OpenHandler;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.InvalidProtocolBufferException;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.proto.ConnectByProto;
import com.sencorsta.ids.common.proto.Entity;
import com.sencorsta.ids.common.proto.utils.ReturnUtils;
import com.sencorsta.ids.common.service.LoginService;
import com.sencorsta.ids.common.service.MysqlService;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.entity.ClientEvent;
import com.sencorsta.ids.core.entity.ErrorMsg;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.LocalMessageHandler;
import com.sencorsta.ids.core.tcp.opensocket.OpenServerBootstrap;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;
import com.sencorsta.utils.string.StringUtil;
import io.netty.channel.Channel;

import java.net.InetSocketAddress;
import java.util.Map;


@ClientEvent("ConnectByProto")
public class ConnectByProtoHandle extends LocalMessageHandler implements RedisService {
    @Override
    public RpcMessage request(Channel channel, JSONObject json, String content, byte[] data, byte[] protobuf) {
        Out.trace("----------------------------ConnectByProto------------------------");
        ConnectByProto.ConnectByProtoRes.Builder res = ConnectByProto.ConnectByProtoRes.newBuilder();
        String olduserId = channel.attr(OpenServerBootstrap.getInstance().KEY_OPENUSER).get().userId;
        if (!StringUtil.isEmpty(olduserId)) {
            return responseProto(res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.RECONNECTION)));
        }
        try {
            ConnectByProto.ConnectByProtoReq req = ConnectByProto.ConnectByProtoReq.parseFrom(protobuf);
            String token = req.getToken();

            JSONObject resMsg = LoginService.login(token, channel);


            Entity.ReturnMsg.Builder msg = Entity.ReturnMsg.newBuilder();

            ErrorMsg jszMsg = (ErrorMsg) resMsg.get("msg");
            if (jszMsg.code == 0) {//塞入管道成功
                Out.trace("-----------------塞入管道成功------------------");
                msg.setCode(jszMsg.code);
                msg.setMsg(jszMsg.Msg);

                //这里的userId是从塞入管道成功得到的userId
                String userId = resMsg.getString("userId");

                //通过userId在redis中取数据
                Map<String, String> userInfo = R_USER.hgetAll(userId);
                res.setPhone(userInfo.get("phone"));//手机号码
                res.setUserId(userId);//用户id
                res.setNickname(userInfo.get("nickname"));//昵称
                res.setPortrait(userInfo.get("portrait"));//头像
                res.setSex(Integer.valueOf(userInfo.get("sex")));//性别
                res.setSignature(userInfo.get("signature"));//签名
                res.setInvitecode(userInfo.get("invitecode"));//邀请码
                res.setIsAgency(Integer.valueOf(userInfo.get("type")));//是否是代理
                {
                    String sql = "select `cardholder`,`cardnumber`,`cardname`,`cardaddress` from `card` where `userId`=?";
                    Object[] args = new Object[]{
                            userId
                    };
                    JSONArray jsonArray = MysqlService.getInstance().select(sql, args);
                    if (jsonArray.size() != 0) {
                        for (var key : jsonArray) {
                            res.addCardList(String.valueOf(key));
                        }
                    }
                }

                Out.debug("----------------------");
                Out.debug(res.getCardListList());
                Out.debug("----------------------");


                res.setMsg(msg);
            } else {
                msg.setMsg(jszMsg.Msg);
                msg.setCode(jszMsg.code);
                res.setMsg(msg);
            }

            return responseProto(res);

        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SERVER_ERROR));
            return responseProto(res);
        }

    }
}
